// import React, { useCallback, useEffect, useState } from 'react';
// import './style.scss';
// import { Button, NavBar, Toast } from 'antd-mobile';
// import { useNavigate } from 'react-router-dom';
// import dp from '../../imgs/deepseek.png';
// // JavaScript
// interface TypeProps {
//   content: string;
//   role?: string;
// }

// const Chat: React.FC = () => {
//   // 定义一个状态变量value，用于存储输入框的值
//   const [value, setValue] = useState('');
//   // 定义一个状态变量list，用于存储聊天记录
//   const [contentList, setContentList] = useState<TypeProps[]>([]);

//   async function startStream(list) {
//     try {
//       const response = await fetch(
//         'https://api.deepseek.com/v1/chat/completions',
//         {
//           method: 'POST',
//           headers: {
//             'Content-Type': 'application/json',
//             Authorization: 'Bearer sk-fea0b31cf6914723942d56735ff617b5', // 替换为实际 API Key
//           },
//           body: JSON.stringify({
//             model: 'deepseek-chat',
//             messages: list,
//             stream: true, // 启用流式传输
//           }),
//         }
//       );

//       const reader = response.body?.getReader() as ReadableStreamDefaultReader<
//         Uint8Array<ArrayBufferLike>
//       >;
//       const decoder = new TextDecoder('utf-8');
//       let resultMessage = '';
//       while (true) {
//         const { done, value } = await reader.read();
//         if (done) break;

//         // 处理流数据块
//         const chunk = decoder.decode(value);
//         const lines = chunk.split('\n').filter((line) => line.trim() !== '');

//         for (const line of lines) {
//           const message = line.replace(/^data: /, '');
//           if (message === '[DONE]') break;

//           try {
//             const parsed = JSON.parse(message);
//             const content = parsed.choices[0]?.delta?.content || '';
//             resultMessage += content;
//             setContentList(
//               list.concat({ role: 'system', content: resultMessage })
//             );
//           } catch (err) {
//             console.error('解析错误:', err);
//           }
//         }
//       }
//     } catch (error) {
//       console.error('请求失败:', error);
//     }
//   }

//   const handleSend = () => {
//     setContentList(contentList.concat({ role: 'user', content: value }));
//   };

//   useEffect(() => {
//     if (contentList.length > 0) {
//       const newList = [...contentList].pop();
//       if (newList?.role === 'user') {
//         startStream(contentList);
//       }
//     }
//   }, [contentList]);

//   return (
//     <div className="chat">
//       <div className="header">
//         <span></span>
//         <span>DeeoSeek</span>
//       </div>
//       <div className="content">
//         {contentList.map((v, i) => {
//           const myClassName =
//             v.role === 'user' ? 'content-right' : 'content-left';
//           const avatar =
//             v.role === 'user'
//               ? 'https://tse3-mm.cn.bing.net/th/id/OIP-C.7GLMYPqMlt2LgkbPsOnDIAAAAA?rs=1&pid=ImgDetMain'
//               : dp;
//           return (
//             <div key={i} className={myClassName}>
//               <div className="avatar">
//                 <img src={avatar} alt="" />
//               </div>
//               <div className="content-box">
//                 <div className="content-message">{v.content}</div>
//               </div>
//             </div>
//           );
//         })}
//       </div>

//       <div className="footer">
//         {/* 受控组件 */}
//         <input
//           className="text"
//           value={value}
//           onChange={(e) => setValue(e.target.value)}
//           onKeyDown={(e) => e.keyCode === 13 && handleSend()}
//         ></input>
//         <Button color="primary" className="send" onClick={() => handleSend()}>
//           发送
//         </Button>
//       </div>
//     </div>
//   );
// };

// export default Chat;

import React, { useState, useEffect } from 'react';
import './style.scss';
import { Button, Toast } from 'antd-mobile';
import dp from '../../imgs/deepseek.png';
import MD from '../../components/md/index';
// 定义消息类型
interface Message {
  content: string;
  role: 'user' | 'system';
}

const Chat: React.FC = () => {
  // 存储输入框的值
  const [inputValue, setInputValue] = useState('');
  // 存储聊天记录
  const [chatMessages, setChatMessages] = useState<Message[]>([]);
  // 存储请求是否正在进行的状态
  const [isLoading, setIsLoading] = useState(false);

  // 发起流式请求的函数
  const startStream = async (messages: Message[]) => {
    setIsLoading(true);
    try {
      const response = await fetch(
        'https://api.deepseek.com/v1/chat/completions',
        // 'https://api.deepseek.com/chat/completions',
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: 'Bearer sk-fea0b31cf6914723942d56735ff617b5', // 替换为实际 API Key
          },
          body: JSON.stringify({
            model: 'deepseek-chat',
            // model: 'deepseek-reasoner',
            messages,
            stream: true,
          }),
        }
      );

      // 检查响应状态码
      if (!response.ok) {
        throw new Error(`请求失败，状态码: ${response.status}`);
      }

      const reader =
        response.body?.getReader() as ReadableStreamDefaultReader<Uint8Array>;
      const decoder = new TextDecoder('utf-8');
      let resultMessage = '';

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value);
        const lines = chunk.split('\n').filter((line) => line.trim() !== '');

        for (const line of lines) {
          const message = line.replace(/^data: /, '');
          if (message === '[DONE]') break;

          try {
            const parsed = JSON.parse(message);
            const content = parsed.choices[0]?.delta?.content || '';
            resultMessage += content;
            setChatMessages([
              ...messages,
              { role: 'system', content: resultMessage },
            ]);
          } catch (err) {
            console.error('解析错误:', err);
          }
        }
      }
    } catch (error) {
      console.error('请求失败:', error);
      Toast.show({
        content: '请求出错，请重试。',
        duration: 2000,
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 处理发送消息的函数
  const handleSend = () => {
    if (inputValue.trim() === '') return;
    const newMessage: Message = { role: 'user', content: inputValue };
    setChatMessages((prevMessages) => [...prevMessages, newMessage]);
    setInputValue('');
  };

  // 监听聊天记录变化，当有新的用户消息时发起请求
  useEffect(() => {
    if (
      chatMessages.length > 0 &&
      chatMessages[chatMessages.length - 1].role === 'user' &&
      !isLoading
    ) {
      startStream(chatMessages);
    }
    document.documentElement.scrollTop = 100000;
  }, [chatMessages, isLoading]);

  return (
    <div className="chat">
      <div className="header">
        <span></span>
        <span>DeepSeek</span>
      </div>
      <div className="content">
        {chatMessages.map((message, index) => {
          const className =
            message.role === 'user' ? 'content-right' : 'content-left';
          const avatar =
            message.role === 'user'
              ? 'https://tse3-mm.cn.bing.net/th/id/OIP-C.7GLMYPqMlt2LgkbPsOnDIAAAAA?rs=1&pid=ImgDetMain'
              : dp;
          return (
            <div key={index} className={className}>
              <div className="avatar">
                <img src={avatar} alt="" />
              </div>
              <div className="content-box">
                {message.role === 'user' ? (
                  <div className="content-message">{message.content}</div>
                ) : (
                  <div className="content-message">{message.content}</div>
                )}
              </div>
            </div>
          );
        })}
      </div>
      <div className="footer">
        <input
          className="text"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          onKeyDown={(e) => e.keyCode === 13 && handleSend()}
          disabled={isLoading}
        />
        <Button
          color="primary"
          className="send"
          onClick={handleSend}
          disabled={isLoading || inputValue.trim() === ''}
        >
          发送
        </Button>
      </div>
    </div>
  );
};

export default Chat;
